<?php
class UserPrivHelper{

	/** 取当前用户权限数组 */
	static function privs(){
		static $list;
		if(!$list){
			$list = Db::get('UserRole')
							->select('purview')
							->join('role')->on('t0.role_id=t1.id')
							->where(array('user_id'=>UID))->getCols();
			if($list){
				$list = array_unique(explode(',', join(',', $list)));
			}
		}
		return $list;
	}

	static function privTree(){
		return (UserAuthHelper::isAdmin())
			? PrivTableHelper::getTree()
			: PrivTableHelper::getTreeForMenu(self::privs());
	}

	/**
	  检查用户是否有特定操作权限
	  */
	static function check($code){
		if(UserAuthHelper::isAdmin()){ return true; }
		static $codes;
		if(!$codes){
			$privs = self::privs();
			if($privs){
				$codes = Db::get('PrivTable')->select('id')->where(array('id','in',$privs))
												->hkey('code')->getCols();
			}
		}
		return isset($codes[$code]);
	}
	
	/**
	 * 检查用户访问当前URL的权限
	 * 先检查当前URL是否在权限表控制范围内，有则验证用户是否有权限，否则允许访问；
	 */
	static function checkurl(){
		if(UserAuthHelper::isAdmin()){ return true; }
		list($cntr, $act) = Core::$action;
		$url = 'show'==$act ? $cntr : "{$cntr}-{$act}";
		if(Db::get('PrivTable')->count()->where(array('url'=>$url))->getCol()){
			return self::check($url);
		}
		return true;
	}

}

?>
